package com.project.server.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.server.common.exception.BusinessException;
import com.project.server.dto.PasswordUpdateDTO;
import com.project.server.dto.UserProfileDTO;
import com.project.server.entity.SysUser;
import com.project.server.mapper.SysUserMapper;
import com.project.server.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class UserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements UserService {

    @Autowired
    private SysUserMapper userMapper;

    @Value("${upload.path}")
    private String uploadPath;

    @Value("${upload.url-prefix}")
    private String urlPrefix;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();


    @Override
    @Transactional
    public void changePassword(Long userId, PasswordUpdateDTO passwordUpdateDTO) {
        SysUser user = getById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 验证原密码
        if (!passwordEncoder.matches(passwordUpdateDTO.getOldPassword(), user.getPassword())) {
            throw new BusinessException("原密码错误");
        }

        // 更新密码
        user.setPassword(passwordEncoder.encode(passwordUpdateDTO.getNewPassword()));
        updateById(user);
    }

    @Override
    @Transactional
    public String uploadAvatar(Long userId, MultipartFile file) throws IOException {
        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            throw new BusinessException("只能上传图片文件");
        }

        // 生成文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename != null ?
            originalFilename.substring(originalFilename.lastIndexOf(".")) : ".jpg";
        String filename = UUID.randomUUID().toString() + extension;

        // 确保上传目录存在
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 保存文件
        File destFile = new File(uploadPath + File.separator + filename);
        file.transferTo(destFile);

        // 更新用户头像
        String avatarUrl = urlPrefix + filename;
        SysUser user = getById(userId);
        user.setAvatar(avatarUrl);
        updateById(user);

        return avatarUrl;
    }
}
